package com.peycard.persistence.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.Query;

import org.apache.commons.collections.CollectionUtils;

import com.peycard.persistence.PersistenceException;
import com.peycard.persistence.dao.local.VinculacionDAOLocal;
import com.peycard.persistence.entities.Company;
import com.peycard.persistence.entities.ReaderList;
import com.peycard.persistence.entities.UserList;
import com.peycard.persistence.entities.Vinculacion;

/**
 * Session Bean implementation class VinculacionDAO
 */
@Stateless
public class VinculacionDAO extends GenericDAOImpl<Vinculacion, Long> implements VinculacionDAOLocal {

    public VinculacionDAO() {
    }

    @Override
    public Vinculacion addVinculacion(String idReader, String idUsr, String idCompany) throws PersistenceException{
    	try{
    		Vinculacion v = new Vinculacion();
    		UserList userList = getEntityManager().find(UserList.class, Long.parseLong(idUsr));
    		Company company = getEntityManager().find(Company.class, Long.parseLong(idCompany));
    		ReaderList reader = getEntityManager().find(ReaderList.class, Long.parseLong(idReader));
    		v.setCompany(company);
    		v.setReaderList(reader);
    		v.setUserList(userList);
    		Vinculacion vinc = super.create(v);
    		return vinc;
    	}catch(Exception e){
    		throw new PersistenceException(e);
    	}
    }
    
    @Override
    public void setDown(String idVinc, String adminUsr) throws PersistenceException{
    	try{
    		Vinculacion v = super.read(Long.parseLong(idVinc));
    		getEntityManager().remove(v);
    	}catch(Exception e){
    		throw new PersistenceException();
    	}
    }
    
    @Override
    public List<Vinculacion> getAll() throws PersistenceException{
    	try{
    		Query query = getEntityManager().createNamedQuery("findAllVinc_1");
    		List<Vinculacion> list = query.getResultList();
    		List<Vinculacion> list2 = new ArrayList<Vinculacion>();
    		if(!CollectionUtils.isEmpty(list)){
    			for(Vinculacion v : list){
    				v.setCompanyName(v.getCompany().getCorporateSpin());
    				v.setUser(v.getUserList().getUsername());
    				v.setNoSerie(v.getReaderList().getSerialNumber());
    				list2.add(v);
    			}
    		}
    		return list2;
    	}catch(Exception e){
    		throw new PersistenceException(e);
    	}
    }
    
}
